﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WiiGeeDotNet.logic
{
  public class Classifier
  {
    private Dictionary<int, GestureModel> m_gesturemodel; // each gesturetype got its own 
    // gesturemodel in this vector
    private double m_lastprob;

    public Classifier()
    {
      this.m_gesturemodel = new Dictionary<int, GestureModel>();
      this.m_lastprob = 0.0;
    }

    /// <summary>
    /// This method recognize a specific gesture, given to the procedure.
    /// For classification a bayes classification algorithm is used.
    /// </summary>
    /// <param name="g">gesture to classify</param>
    /// <returns></returns>
    public GestureModel ClassifyGesture(Gesture _gesture)
    {
      // Wert im Nenner berechnen, nach Bayes
      double sum = 0;
      foreach (GestureModel g in m_gesturemodel.Values)
      {
        sum += g.GetDefaultProbability() * g.Matches(_gesture);
      }

      GestureModel recognized = null; // which gesture has been recognized
      double recogprob = Int32.MinValue; // probability of this gesture
      double probgesture = 0; // temporal value for bayes algorithm
      double probmodel = 0; // temporal value for bayes algorithm
      foreach(GestureModel g in m_gesturemodel.Values)
      {
        //this.gesturemodel[i].print(); // Debug
        double tmpgesture = g.Matches(_gesture);
        double tmpmodel = g.GetDefaultProbability();

        if (((tmpmodel * tmpgesture) / sum) > recogprob)
        {
          probgesture = tmpgesture;
          probmodel = tmpmodel;
          recogprob = ((tmpmodel * tmpgesture) / sum);
          recognized = g;
        }
      }

      // a gesture could be recognized
      if (recogprob > 0 && probmodel > 0 && probgesture > 0 && sum > 0)
      {
        this.m_lastprob = recogprob;
        return recognized;
      }
      else
      {
        // no gesture could be recognized
        return null;
      }

    }

    public double GetLastProbability()
    {
      return this.m_lastprob;
    }

    public void AddGestureModel(GestureModel gm)
    {
      this.m_gesturemodel.Add(gm.Id, gm);
    }

    public Dictionary<int, GestureModel> GestureModels
    {
      get {return this.m_gesturemodel;}
    }

    public void Clear()
    {
      this.m_gesturemodel = new Dictionary<int,GestureModel>();
    }
  }
}
